package mobilesmil.xml.parsing;

import java.io.FileReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import mobilesmil.data.SmilDataSet;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.os.Environment;

/**
 * Uses {@link SmilHandler} to construct a {@link SmilDataSet} from a SMIL XML document.
 * @author Ryan Ware
 *
 */
public class SmilParser {
	
	/**
	 * Constructs a {@link SmilDataSet} by parsing a SMIL XML document.
	 * @param fileName {@link String} file name of SMIL XML document
	 * @return {@link SmilDataSet} constructed from the parsed XML document
	 * @throws Exception if XML document cannot be parsed into a {@link SmilDataSet}
	 */
	public static SmilDataSet getParsedDataSet(String fileName) throws Exception
	{
		String SDCardDir = Environment.getExternalStorageDirectory().toString() + "/";
		
		if(fileName.startsWith(SDCardDir)) {
			fileName = fileName.replace(SDCardDir, "");
		}
		if(fileName.endsWith(".smil")) {
			fileName = fileName.replace(".smil", "");
		}
		
		FileReader f = new FileReader(SDCardDir + fileName + ".smil");
    	
        // get a SAXParser from the SAXPArserFactory
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        // get the XMLReader of the SAXParser
        XMLReader xr = sp.getXMLReader();
        // create a new ContentHandler and apply it to the XMLReader
        SmilHandler mySmilHandler = new SmilHandler();
        xr.setContentHandler(mySmilHandler);
        
        // parse the XML data
        xr.parse(new InputSource(f));

        // the SmilHandler now provides the parsed data to us
        SmilDataSet parsedDataSet = mySmilHandler.getParsedData();
        parsedDataSet.setFileName(fileName);
        return parsedDataSet;
	}
	
}
